// Context.cpp
//
#include "Context.h"

#include "OpenGL.h"


#include <string>
#include <iostream>

using namespace OpenGL;

// ------------------------------------------------------------------------------------------------
Context::Context( void *winID )
{
	create(winID);
	makeCurrent();
}

// ------------------------------------------------------------------------------------------------
Context::~Context()
{
	destroy();
}

// ------------------------------------------------------------------------------------------------
void Context::create( void *winID )
{
	if( !winID )
		return;

	PIXELFORMATDESCRIPTOR pfd;

	memset(&pfd,0,sizeof(pfd));

	pfd.nSize	    = sizeof(PIXELFORMATDESCRIPTOR);
	pfd.nVersion	= 1;
	pfd.dwFlags		= PFD_DRAW_TO_WINDOW | PFD_SUPPORT_OPENGL | PFD_DOUBLEBUFFER;
	pfd.iPixelType	= PFD_TYPE_RGBA;
	pfd.dwLayerMask	= PFD_MAIN_PLANE;
	pfd.cColorBits  = 32;
	pfd.cDepthBits  = 24;

	hwnd = (HWND)winID;
	hDC  = GetDC((HWND)hwnd);	
	if(hDC == NULL)
	{
		destroy();
		return;
	}

	int pxlfmt = ChoosePixelFormat((HDC)hDC,&pfd);
	if(!pxlfmt || !SetPixelFormat((HDC)hDC,pxlfmt,&pfd))
	{
		destroy();
		return;
	}
	
	if(!(hRC = wglCreateContext((HDC)hDC)))
	{
		destroy();
		return;
	}
}

// ------------------------------------------------------------------------------------------------
void Context::destroy()
{
	if(hRC)
	{
		wglMakeCurrent(NULL,NULL);
		wglDeleteContext((HGLRC)hRC);
		hRC = NULL;
	}

	if(hDC && !ReleaseDC((HWND)hwnd,(HDC)hDC))
		hDC = NULL;
}

// ------------------------------------------------------------------------------------------------
void Context::makeCurrent()
{
	wglMakeCurrent((HDC)hDC,(HGLRC)hRC);
}

// ------------------------------------------------------------------------------------------------
void Context::swapBuffers()
{
	SwapBuffers((HDC)hDC);
}

// ------------------------------------------------------------------------------------------------
void Context::enableVSync(bool enabled)
{
	//if( glewIsSupported("wglSwapIntervalEXT") )
       // wglSwapIntervalEXT(enabled ? 1 : 0);
}